package com.eg366.nioLearn.baseSocket.chapter04;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

/**
 * TCP客户端
 * 客户端向服务器发起连接请求后，就被动的等待服务器的响应
 */
public class TCPEchoClient {
	public static void main(String[] args) throws UnknownHostException, IOException {
		args = new String[]{"127.0.0.1", "Echo this !", "1122"};
		if ((args.length < 2) || (args.length > 3)) {
			throw new IllegalArgumentException("Parameter(s):<server> <word> [<port>]");
		}
		
		/* socket服务器端的主机名或IP */
		String server = args[0];
		byte[] data = args[1].getBytes();
		/* 端口号，若参数中没传，默认为7 */
		int servPort = (args.length == 3) ? (Integer.parseInt(args[2])) : 7;
		
		/* 创建TCP套接字 */
		Socket socket = new Socket(server, servPort);
		System.out.println("Connected to server .. sending echo string");
		
		/* 获取套接字的输入、输出流 */
		InputStream in = socket.getInputStream();
		OutputStream out = socket.getOutputStream();
		
//		DataOutputStream out1 = new DataOutputStream(new BufferedOutputStream(out));
		
		out.write(data);
		
		int totalBytesRcvd = 0;
		int bytesRcvd;
		/**
		 * 注意:之所以用while循环用多个read来接收返回数据，因为返回数据时的返回数据被TCP协议分割成多个部分进行返回
		 * 当套接字socket连接被另一端关闭，read方法返回-1
		 */
		while(totalBytesRcvd < data.length) {
			if((bytesRcvd = in.read(data, totalBytesRcvd, data.length - totalBytesRcvd)) == -1) {
				throw new SocketException("Connection closed prematurely");
			}
			totalBytesRcvd += bytesRcvd;
		}
		
		System.out.println("Received:" + new String(data));
		
		/* 关闭套接字socket连接 */
		socket.close();
	}
}
